#!/usr/bin/env python3
"""
最小化API测试 - 假设服务器在运行
"""

import requests
import json
import time
from datetime import datetime

# 配置
BASE_URL = "http://localhost:8000"
ADMIN_TOKEN = "admin_secret_token_2024"

def test_endpoint(method, url, headers=None, json_data=None, description=""):
    """测试单个端点"""
    try:
        if method.upper() == "GET":
            response = requests.get(url, headers=headers, timeout=10)
        elif method.upper() == "POST":
            response = requests.post(url, headers=headers, json=json_data, timeout=10)
        elif method.upper() == "PUT":
            response = requests.put(url, headers=headers, json=json_data, timeout=10)
        elif method.upper() == "DELETE":
            response = requests.delete(url, headers=headers, timeout=10)
        else:
            print(f"❌ 不支持的方法: {method}")
            return False
        
        success = response.status_code in [200, 201]
        status = "✅ PASS" if success else "❌ FAIL"
        
        print(f"{status} {method} {url}")
        print(f"   描述: {description}")
        print(f"   状态码: {response.status_code}")
        
        if success and response.content:
            try:
                data = response.json()
                if isinstance(data, list):
                    print(f"   返回: 列表，{len(data)} 项")
                elif isinstance(data, dict):
                    print(f"   返回: 对象，{len(data)} 个字段")
                else:
                    print(f"   返回: {type(data)}")
            except:
                print(f"   返回: 非JSON数据")
        elif not success:
            try:
                error = response.json()
                print(f"   错误: {error}")
            except:
                print(f"   错误: {response.text[:100]}")
        
        print()
        return success
        
    except requests.exceptions.ConnectionError:
        print(f"❌ FAIL {method} {url}")
        print(f"   描述: {description}")
        print(f"   错误: 连接失败 - 服务器可能未运行")
        print()
        return False
    except Exception as e:
        print(f"❌ FAIL {method} {url}")
        print(f"   描述: {description}")
        print(f"   错误: {str(e)}")
        print()
        return False

def main():
    print("🧪 API接口测试 (假设服务器运行在 http://localhost:8000)")
    print("="*70)
    
    results = []
    
    # 基础健康检查
    print("📋 基础接口测试")
    print("-" * 30)
    results.append(test_endpoint("GET", f"{BASE_URL}/health", description="健康检查"))
    results.append(test_endpoint("GET", f"{BASE_URL}/", description="根路径"))
    
    # 学生端API
    print("🎓 学生端API测试")
    print("-" * 30)
    results.append(test_endpoint("GET", f"{BASE_URL}/api/questions", description="获取题目列表"))
    
    # 提交答案测试
    submit_data = {
        "student_name": "API测试学生",
        "class_id": 1,
        "answers": [{"questionId": 1, "selectedAnswer": "A"}]
    }
    results.append(test_endpoint("POST", f"{BASE_URL}/api/submit", json_data=submit_data, description="提交答案"))
    
    results.append(test_endpoint("GET", f"{BASE_URL}/api/scores/1", description="获取班级成绩"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/class-analysis/1", description="班级分析"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/student-trajectory/1/API测试学生", description="学生轨迹"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/error-analysis/1", description="错题分析"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/teaching-suggestions/1", description="教学建议"))
    
    # 教师端API
    print("👨‍🏫 教师端API测试")
    print("-" * 30)
    results.append(test_endpoint("GET", f"{BASE_URL}/api/teacher/dashboard?class_id=1", description="教师数据看板"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/teacher/dashboard/overview?class_id=1", description="数据看板概览"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/teacher/dashboard/students?class_id=1", description="学生数据"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/teacher/dashboard/errors?class_id=1", description="错题数据"))
    results.append(test_endpoint("GET", f"{BASE_URL}/api/teacher/dashboard/suggestions?class_id=1", description="教学建议"))
    
    # 管理员API
    print("🔧 管理员API测试")
    print("-" * 30)
    admin_headers = {"Authorization": f"Bearer {ADMIN_TOKEN}"}
    
    results.append(test_endpoint("GET", f"{BASE_URL}/admin/questions", headers=admin_headers, description="获取所有题目"))
    results.append(test_endpoint("GET", f"{BASE_URL}/admin/question-banks", headers=admin_headers, description="获取所有题库"))
    results.append(test_endpoint("GET", f"{BASE_URL}/admin/question-banks/active", headers=admin_headers, description="获取激活题库"))
    
    # 创建题目测试
    question_data = {
        "questionContent": "API测试题目：什么是HTTP？",
        "optionA": "超文本传输协议",
        "optionB": "文件传输协议",
        "optionC": "邮件传输协议",
        "optionD": "网络传输协议",
        "answer": "A",
        "knowledgePoint": "网络协议",
        "explanation": "HTTP是HyperText Transfer Protocol的缩写",
        "questionBankId": 1
    }
    results.append(test_endpoint("POST", f"{BASE_URL}/admin/questions/create", headers=admin_headers, json_data=question_data, description="创建题目"))
    
    # 题库管理
    bank_data = {
        "name": "API测试题库",
        "description": "用于API测试的题库",
        "created_by": "API测试",
        "is_active": 0
    }
    results.append(test_endpoint("POST", f"{BASE_URL}/admin/question-banks", headers=admin_headers, json_data=bank_data, description="创建题库"))
    
    # 其他管理员接口
    results.append(test_endpoint("GET", f"{BASE_URL}/admin/class-config", description="获取班级配置"))
    results.append(test_endpoint("GET", f"{BASE_URL}/admin/llm-configs", headers=admin_headers, description="获取LLM配置"))
    
    # 统计结果
    print("📊 测试结果统计")
    print("="*70)
    total_tests = len(results)
    passed_tests = sum(results)
    failed_tests = total_tests - passed_tests
    
    print(f"总测试数: {total_tests}")
    print(f"通过: {passed_tests} ✅")
    print(f"失败: {failed_tests} ❌")
    print(f"成功率: {(passed_tests/total_tests*100):.1f}%")
    
    if failed_tests == 0:
        print("\n🎉 所有API接口测试通过！")
    elif passed_tests == 0:
        print("\n⚠️  所有测试失败 - 请检查服务器是否运行")
        print("启动服务器命令: python backend/main.py")
    else:
        print(f"\n⚠️  部分测试失败，请检查失败的接口")
    
    # 保存结果
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    report_file = f"api_test_report_{timestamp}.txt"
    
    with open(report_file, 'w', encoding='utf-8') as f:
        f.write(f"API接口测试报告\n")
        f.write(f"测试时间: {datetime.now()}\n")
        f.write(f"总测试数: {total_tests}\n")
        f.write(f"通过: {passed_tests}\n")
        f.write(f"失败: {failed_tests}\n")
        f.write(f"成功率: {(passed_tests/total_tests*100):.1f}%\n")
    
    print(f"\n📄 详细报告已保存到: {report_file}")

if __name__ == "__main__":
    main()
